package com.home.jinlanhua.utils;

import com.home.jinlanhua.exception.ServiceException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    public static void main(String[] args) {
        System.out.println(getMD5Code("123456"));
    }


    /**
     * MD5 加密
     *
     * @param str
     * @return
     */
    public static String getMD5Code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            String result = bytetoString(md.digest(str.getBytes()));
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new ServiceException("加密失败");
        }
    }

    public static String bytetoString(byte[] digest) {
        String str = "";
        String tempStr = "";

        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }
}
